<template>
  <div class="page">
    <div class="tools-bar">
      <div class="left-wrap">
        <div  class="mRight_150" >
        <el-button size="small" type="primary" @click="returnList">返回</el-button>
        </div>
        <el-input prefix-icon="el-icon-search"  placeholder="请输入url" size="small" v-model="searchKey"></el-input>
        <el-button size="small" type="primary" @click="handleSearch">查询</el-button>
        <el-button size="small" type="warning" @click="cleanSearch">重置</el-button>
        <!-- {{moduleId(type)}} -->
        <el-button type="primary" size="small" @click="handleAddApp">新增</el-button>
      </div>
    </div>
    <el-table
      :data="tableData4"
      style="width: 100%">
      <el-table-column
        prop="appName"
        label="应用名称"
        align="center">
      </el-table-column>
      <el-table-column
        prop="gsId"
        label="GID"
        width="280"
        align="center">
      </el-table-column>
      <el-table-column
        prop="url"
        label="URL"
        align="center">
      </el-table-column>
      <el-table-column
        prop="realmName"
        label="域名"
        align="center">
      </el-table-column>
      <el-table-column
        prop="protocol"
        label="协议"
        align="center">
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        align="center">
      </el-table-column>
      <el-table-column
        prop="isDelete"
        label="状态"
        align="center">
        <template slot-scope="scope">
          <el-tag size="small" type="info" v-if="scope.row.isDelete == 1">
            禁用
          </el-tag>
          <el-tag size="small" type="success" v-if="scope.row.isDelete == 0">
            启用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" icon="el-icon-delete" size="small" @click="deleteServer(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination ref="pageInfo" :total="pageInfo.totalElements" :page.sync="pageInfo.currentPage" @pagination="pagination"></pagination>
    <el-dialog title="服务器新增或编辑" :visible.sync="dialogFormVisible">
      <el-form :model="serverForm" :rules="rules" ref="serverForm" label-width="100px" class="demo-serverForm">
        <el-form-item label="url" prop="url" >
          <el-input class="text-width" v-model="serverForm.url"></el-input>
        </el-form-item>
        <el-form-item label="协议" prop="protocolId">
          <template>
            <el-select v-model="serverForm.protocolId" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.agreementCode"
                :label="item.agreementName"
                :value="item.agreementCode">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="地区" prop="region">
          <template>
            <el-select v-model="serverForm.region" placeholder="请选择">
              <el-option
                v-for="item in regions"
                :key="item.countryId"
                :label="item.chineseName"
                :value="item.countryId">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="域名" prop="realmName">
          <el-input class="text-width" v-model="serverForm.realmName"></el-input>
          <el-input v-model="serverForm.realmName"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input class="text-width" type="textarea" v-model="serverForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { api } from '@/utils'
import { pagination } from '@/components'
import { validateURL } from '../../utils/validate'
export default {
  methods: {
    // 跳转到list页面
    returnList () {
      this.$router.push({
        path: 'list'
      })
    },
    deleteServer (data) {
      this.$confirm('是否删除服务器, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.request({
          url: api.deleteServer,
          method: 'post',
          params: {
            id: data['id']
          }
        }).then(data => {
          if (data.code === 200) {
            this.$message({
              message: data.msg,
              duration: 2000,
              type: 'success',
              center: true
            })
            this.dialogFormVisible = false
            this.getData({
              applicationId: this.appId
            })
          } else {
            this.$message({
              message: '删除失败',
              duration: 2000,
              type: 'error',
              center: true
            })
          }
        })
      })
    },
    cleanForm (data) {
      Object.keys(data).forEach(function (key) {
        data[key] = ''
      })
    },
    handleAddApp () {
      this.dialogFormVisible = true
      // 清空form中的数据
      this.cleanForm(this.serverForm)
    },
    handleEdit (data) {
      console.log(data)
      this.serverForm = data
      this.dialogFormVisible = true
    },
    submit () {
      let url = ''
      if (this.serverForm.id !== '') {
        url = api.editServer
      } else {
        url = api.addServer
      }
      this.$refs['serverForm'].validate((valid) => {
        if (valid) {
          delete this.serverForm['updateDate']
          delete this.serverForm['createDate']
          this.serverForm.applicationId = this.appId

          let regUrl = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
          let regRm = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/

          if (this.serverForm['url'] == "" && this.serverForm['realmName'] == "") {
            this.$message({message: 'IP和域名请任意填一个',
              type: 'error', center: true})
            return false
          }

          if (this.serverForm['url'] != "" && !regUrl.test(this.serverForm['url'])){
            this.$message({message: 'IP填写错误,请重新输入',
              type: 'error', center: true})
            return false
          }

          if (this.serverForm['realmName'] != "" && !regRm.test(this.serverForm['realmName'])){
            this.$message({message: '域名填写错误,请重新输入',
              type: 'error', center: true})
            return false
          }

          this.$axios.request({
            url: url,
            method: 'post',
            params: this.serverForm
          }).then(data => {
            if (data.code === 200) {
              this.$message({
                message: data.msg,
                duration: 2000,
                type: 'success',
                center: true
              })
              this.dialogFormVisible = false
              this.getData({
                applicationId: this.appId
              })
            } else {
              this.$message({
                message: '保存失败',
                duration: 2000,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    handleSearch () {
      let params = {}
      params.url = this.searchKey
      params.applicationId = this.appId
      this.getData(params)
    },
    cleanSearch () {
      this.searchKey = ''
    },
    // 列表分页操作事件
    pagination (e) {
      let params = {}
      params.pageNum = e.page
      params.pageSize = e.limit
      this.getData(params)
    },
    // 获取数据
    getData (param) {
      this.$axios.request({
        url: api.getServerList,
        method: 'post',
        params: param
      }).then(data => {
        this.pageInfo.totalElements = data.total
        let result = data.data
        if (data.success === true) {
          this.tableData4 = result
        } else {
          this.$message({
            message: '请求失败',
            duration: 2000,
            type: 'error'
          })
        }
      })
    },
    // 获取协议数据
    getSelectData () {
      const scope = this
      this.$axios.request({
        url: api.getProtoData,
        method: 'post'
      }).then(res => {
        let result = res['data']
        if (res.success === true) {
          scope.options = result
        }
      })

      this.$axios.request({
        url: api.getRegionsData,
        method: 'post'
      }).then(res => {
        let result = res['data']
        if (res.success === true) {
          scope.regions = result
        }
      })
    }
  },
  components: {
    pagination
  },
  data () {
    return {
      labelPosition: 'right',
      appId: this.$router.history.current.query.appId,
      tableData4: [],
      searchKey: '',
      serverForm: {
        id: '',
        url: '',
        applicationId: '',
        realmName: '',
        remark: '',
        protocolId: '',
        region: ''
      },
      rules: {
        protocolId: [
          { required: true, message: '请输入协议', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请输入区域', trigger: 'blur' }
        ]
      },
      dialogFormVisible: false,
      options: [],
      regions: [],
      pageInfo: {
        totalElements: 0,
        currentPage: 1
      }
    }
  },
  mounted () {
    this.getData({
      applicationId: this.appId
    })
    this.getSelectData()
  },
  watch: {
    $route: {
      handler: function () {
        this.appId = this.$router.history.current.query.appId
        if (this.appId !== undefined) {
          this.getData({
            'applicationId': this.appId
          })
        }
      },
      deep: true
    }
  }
}
</script>
